﻿using System;
using System.Web.Mvc;
using Framework.Serializer;
using System.Web;
namespace Framework.Mvc.Util
{
    public class JsonpResult : JsonResult
    {
       
        /// <summary>
        /// 
        /// </summary>
        public JsonpResult()
        {
            JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        }


        private const string CallbackApplicationType = "application/json";

        /// <summary>
        /// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
        /// </summary>
        /// <param name="context">The context within which the result is executed.</param>
        /// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
        public override void ExecuteResult(ControllerContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }
            var reponse = context.HttpContext.Response;
            //content type
            reponse.ContentType = ContentType.Or(CallbackApplicationType);
            //content encoding
            if (ContentEncoding != null)
            {
                reponse.ContentEncoding = ContentEncoding;
            }
            //
            var serializedData = Data.SToStringJson();
            // callback
            string callback = RequestExtention.GetString("callback");
            if (!callback.IsBlank())
            {
                serializedData = string.Format("{0}({1})", callback, serializedData);
            }
            reponse.Write(serializedData);
        }
    }

    
}
